//
//  STKAudioPlayerHandle.m
//  音乐播放器
//
//  Created by dllo on 16/5/4.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "STKAudioPlayerHandle.h"
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface STKAudioPlayerHandle ()<STKAudioPlayerDelegate>

@property (nonatomic, strong)NSIndexPath *indexPath;
@property (nonatomic, assign)BOOL inscrease;


@end



@implementation STKAudioPlayerHandle

+ (instancetype)shareSTKAudioPlayerHandle {
    static STKAudioPlayerHandle *audioPlayerHandle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        audioPlayerHandle = [[STKAudioPlayerHandle alloc] init];
    });
    return audioPlayerHandle;
}

- (void)getSongs:(NSNotification *)noti {
//    NSLog(@"sklfklsdfjsdkf");
    _mutableArray = [NSMutableArray arrayWithArray:[noti object]];
    NSLog(@"%ld",self.mutableArray.count);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HandelArr" object:self.mutableArray];
}

- (void)getCurrentIndexPath:(NSNotification *)noti {
    self.indexPath = [noti object];
    self.currentOfMusic = [self.indexPath row];
    self.audioPlayer = [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayer];
    self.audioPlayerStyle = [[[NSUserDefaults standardUserDefaults] valueForKey:@"audioPlayerStyle"] integerValue];
    [self playMusic];
    
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didCancelQueuedItems:(NSArray *)queuedItems {
//    NSLog(@"6");
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId {
//    NSLog(@"5");
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration {
    NSLog(@"播放完成");
    if ((stopReason == STKAudioPlayerStopReasonNone || stopReason == STKAudioPlayerStopReasonEof)&&(self.audioPlayer.state == STKAudioPlayerStateRunning)) {
        NSLog(@"1");
        [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] playStyleWithOrder:NO];
    }
    if (stopReason == STKAudioPlayerStateBuffering && self.audioPlayer.state == STKAudioPlayerStateRunning) {
        [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] playStyleWithOrder:NO];
        NSLog(@"2");
    }
    if (stopReason == STKAudioPlayerStopReasonEof) {
        [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] playStyleWithOrder:NO];
        NSLog(@"3");
    }
    if (self.audioPlayer.state == STKAudioPlayerStateStopped) {
        [[STKAudioPlayerHandle shareSTKAudioPlayerHandle] playStyleWithOrder:NO];
        NSLog(@"4");
    }
    
}


- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId {
//    NSLog(@"4");
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState {
//    NSLog(@"3");
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer logInfo:(NSString *)line {
//    NSLog(@"2`");
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode {
//    NSLog(@"1");
}

- (void)setAudioPlayer:(STKAudioPlayer *)audioPlayer withPlayStyle:(STKAudioPlayerPlayStyle)audioPlayerPlaySytle {
    self.audioPlayerStyle = audioPlayerPlaySytle;
}

- (void)playMusic {
//    NSLog(@"%ld",self.currentOfMusic);
    PosterDetailSongsModel *DetailModel =self.mutableArray[self.currentOfMusic];
    AuditionListModel *auditionModel = DetailModel.auditionList.lastObject;
//    NSLog(@"%@",auditionModel.)
    NSString *string = auditionModel.url;
//    NSLog(@"%@",string);
    if ((!string && self.audioPlayerStyle != STKAudioPlayerPlayminiSingleLoop) || [string isEqualToString:@"(null)"]) {
//        NSLog(@"33");
//        NSLog(@"%@",string);
//        if ([self respondsToSelector:@selector(nextSonger)]) {
////            NSLog(@"55");
//        } else if ([self respondsToSelector:@selector(lastSonger)]) {
////            NSLog(@"66");
//        }
        if (self.inscrease) {
            [self nextSonger];
        } else {
            [self lastSonger];
        }
        
        
    } else {
        self.audioPlayer.state = STKAudioPlayerStateStopped;
        
    }
    if (string) {

        [self.audioPlayer play:string];
        self.audioPlayer.volume = 1;
//        NSLog(@"%@",string);
    }
}

- (NSMutableArray *)mutableArray {
    if (_mutableArray == nil) {
        _mutableArray = [NSMutableArray array];
    }
    return _mutableArray;
}
- (STKAudioPlayer *)audioPlayer {
    if (_audioPlayer == nil) {
        _audioPlayer = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000}}];
        self.audioPlayerStyle = [[[NSUserDefaults standardUserDefaults] valueForKey:@"audioPlayerStyle"] integerValue];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getSongs:) name:@"songs" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCurrentIndexPath:) name:@"playMusic" object:nil];
        _audioPlayer.delegate = self;
        
         //后台播放音频设置
//        AVAudioSession *session = [AVAudioSession sharedInstance];
//        [session setActive:YES error:nil];
//        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playOr:) name:@"player" object:nil];
//        [self addObserver:self forKeyPath:@"currentOfMusic" options:NSKeyValueChangeNewKey ||NSKeyValueChangeOldKey context:nil];
    }
//    self.audioPlayerStyle = [[[NSUserDefaults standardUserDefaults] valueForKey:@"audioPlayerStyle"] integerValue];
    return _audioPlayer;
}


- (void)setPlayerPlayStyle {
    if (self.audioPlayerStyle == STKAudioPlayerPlayminiSingleLoop) {
        [self setAudioPlayerStyle:STKAudioPlayerRandom];
    } else if (self.audioPlayerStyle == STKAudioPlayerRandom) {
        [self setAudioPlayerStyle:STKAudioPlayerAllLoop];
    } else {
        [self setAudioPlayerStyle:STKAudioPlayerPlayminiSingleLoop];
        
    }
    NSLog(@"11111111");
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSString stringWithFormat:@"%ld",(long)self.audioPlayerStyle] forKey:@"audioPlayerStyle"];
    [userDefaults synchronize];
    NSLog(@"%ld",self.audioPlayerStyle);
    NSLog(@"%@",[userDefaults valueForKey:@"audioPlayerStyle"]);
}

- (void)lastSonger {
    self.inscrease = NO;
    [self playStyleWithOrder:YES];
    
}

- (void)nextSonger {
    self.inscrease = YES;
    [self playStyleWithOrder:NO];
}

- (void)playStyleWithOrder:(BOOL)order {
    if ([[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayerStyle] == STKAudioPlayerAllLoop) {
        
        if (!order) {
         
            self.currentOfMusic = self.currentOfMusic + 1;
          
            if (self.currentOfMusic == self.mutableArray.count) {
                self.currentOfMusic = 0;
             
            }
        } else {
            
            
            if (self.currentOfMusic == 0) {
                self.currentOfMusic = self.mutableArray.count - 1;
            } else {
                self.currentOfMusic = self.currentOfMusic - 1;
            }
        }
        
    } else if ([[STKAudioPlayerHandle shareSTKAudioPlayerHandle] audioPlayerStyle] == STKAudioPlayerRandom) {
     NSLog(@"1");
        self.currentOfMusic = arc4random() % self.mutableArray.count;
    } else {
        NSLog(@"1");
        self.currentOfMusic = self.currentOfMusic;
    }
//    NSLog(@"kdsjkdlsf");
    [self playMusic];
}


- (void)pauseOrResumePlayer {
    
        if (self.audioPlayer.state == STKAudioPlayerStatePlaying) {
            [self.audioPlayer pause];
        } else if (self.audioPlayer.state == STKAudioPlayerStatePaused){
            [self.audioPlayer resume];
        } else if (self.audioPlayer.state == STKAudioPlayerStateStopped && self.audioPlayer.stopReason == STKAudioPlayerStopReasonEof) {
            [self nextSonger];
        }
    
}



@end
